import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//  现在vue3的路由
// 1. 创建路由实例 createRouter({配置对象})
// 2. 配置选项中 routes; 【路由规则】
// 3. createWebHistory 使用路由history 模式
// 4. crrateWebHashHistory 使用路由hash模式

const router = createRouter({
  // 路由的基准路径 create-vit 脚手架提供的数据 环境变量 import.meta.env.BASE_URL 基准地址 默认/
  //history: createWebHistory history模式
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
      meta: { title: '登录' },
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' },
        },
        {
          path: '/article',
          name: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' },
        },
        {
          path: '/notify',
          name: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' },
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' },
        },
      ],
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' },
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
      meta: { title: '极速问诊' },
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
      meta: { title: '选择科室' },
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' },
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' },
    },
    {
      // 支付失败
      path: '/room',
      component: () => import('@/views/Room/index.vue'),
      meta: { title: '问诊室' },
      beforeEnter(to) {
        if (to.query.payResult === 'false') return '/user/consult'
      },
    },
  ],
})
// 路由前置守卫
router.beforeEach((to) => {
  // 处理进度条
  NProgress.start()
  // 用户仓库 是否有token
  const store = useUserStore()
  // 不需要登录的页面， 白名单
  const wihteList = ['/login']
  // 如果没有登录且不在白名单内，去登陆
  if (!store.user?.token && !wihteList.includes(to.path)) return '/login'
  // 否则不做处理
})
// 路由后置守卫
router.afterEach((to) => {
  // 修改标题
  document.title = `149优医问诊-${to.meta.title || ''}`
  NProgress.done()
})
NProgress.configure({
  showSpinner: false,
})

export default router
